package org.findbugs.report.messages;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.findbugs.report.entity.exception.ReportException;

public class Messages {

    private static Document messages;
    
    private static final String CATEGORY = "//BugCategory[@category='";
    private static final String BUG = "//BugPattern[@type='";

    public BugCategory getCategory(String categoryId) throws ReportException {
        initialize();
        String xpath = prepareXPath(CATEGORY, categoryId);
        Node categoryNode = messages.selectSingleNode(xpath);
        return BugCategory.create(categoryNode);
    }
    
    public BugPattern getBug(String bugId) throws ReportException {
        initialize();
        String xpath = prepareXPath(BUG, bugId);
        Node bugNode = messages.selectSingleNode(xpath);
        return BugPattern.create(bugNode);
    }

    private void initialize() throws ReportException {
        if (messages == null) {
            SAXReader reader = new SAXReader();
            try {
                messages = reader.read(this.getClass().getResourceAsStream("/messages.xml"));
            } catch (DocumentException e) {
                throw new ReportException(e.getMessage());
            }
        }
    }
    
    private String prepareXPath(String base, String id) {
        return base + id + "']";
    }

}
